package com.mapull.web;

import com.mapull.entity.Product;
import com.mapull.entity.ProductEnum;
import com.mapull.entity.ProductTypeConverter;
import com.mapull.entity.TypeEnum;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: mapull
 * @description: ProductController
 * @date:2020/03/21
 **/
@RestController
@RequestMapping("/product")
public class ProductController {

    @GetMapping("/type")
    public Product findByType(TypeEnum type) {
        System.out.println(type);
        if (TypeEnum.BOOK.equals(type)) {
            return new Product(49.9, "Think in Java", TypeEnum.BOOK);
        }
        return null;
    }

    @ApiImplicitParam(name = "type", paramType = "query", allowableValues = "BOOK,FOOD,OTHER", allowMultiple = true)
    @GetMapping("/types")
    public Product findByTypes(TypeEnum[] type) {
        System.out.println(type);
        if (TypeEnum.BOOK.equals(type[0])) {
            return new Product(49.9, "Think in Java", TypeEnum.BOOK);
        }
        return null;
    }

    @ApiImplicitParam(name = "type", paramType = "query", allowableValues = "书籍,食物")
    @GetMapping("/query")
    public Product queryByType(String type) {
        ProductEnum productEnum = ProductEnum.fromType(type);
        return new Product(49.9, "Think in Java", TypeEnum.BOOK);
    }

    @InitBinder
    public void initBean(WebDataBinder webDataBinder) {
        webDataBinder.registerCustomEditor(ProductEnum.class, new ProductTypeConverter());
    }
}
